from flask import Flask, request, jsonify, send_from_directory, g, render_template
import sqlite3
import logging

app = Flask(__name__, static_folder='static', template_folder='templates')

@app.route('/test_static')
def test_static():
    return send_from_directory('static', 'styles.css')
# 设置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 创建或连接数据库
def get_db_connection():
    conn = sqlite3.connect('temporary_passwords.db')
    conn.row_factory = sqlite3.Row
    return conn

@app.teardown_appcontext
def close_db_connection(exception):
    conn = getattr(g, '_database', None)
    if conn is not None:
        conn.close()

# 管理员账户名和密码
ADMIN_USERNAME = 'Administrator'
ADMIN_PASSWORD = 'ABCDEFG'

# 修改管理员密码
@app.route('/change-admin-password', methods=['POST'])
def change_admin_password():
    db = get_db_connection()
    g._database = db  # 存储数据库连接到 g 对象
    current_password = request.json.get('current_password')
    new_password = request.json.get('new_password')
    if not current_password or not new_password:
        return jsonify({'message': 'Current and new password are required'}), 400
    if current_password != ADMIN_PASSWORD:
        return jsonify({'message': 'Incorrect current password'}), 403
    try:
        db.execute('UPDATE users SET password = ? WHERE username = ?', (new_password, ADMIN_USERNAME))
        db.commit()
        ADMIN_PASSWORD = new_password  # 更新全局变量
        logging.info('Admin password changed successfully.')
        return jsonify({'message': 'Admin password changed successfully'}), 200
    except Exception as e:
        logging.error(f'Error changing admin password: {str(e)}')
        return jsonify({'message': 'Error changing admin password'}), 500

# 路由以提供前端页面
@app.route('/')
def home():
    return render_template('Website_front_end.html')

@app.route('/main_content')
def show_main_content():
    return render_template('main_content.html')

@app.route('/main_content.html')
def main_content_html():
    return render_template('main_content.html')

# 验证密码的路由
@app.route('/verify-password', methods=['POST'])
def verify_password():
    password = request.json.get('password')
    if password == ADMIN_PASSWORD:
        return jsonify({'message': 'Access granted'})
    else:
        return jsonify({'message': 'Password expired or invalid'}), 403

if __name__ == '__main__':
    app.run(debug=True)